﻿/*========================== 
 * @author 郑金泉
 * @desc 网络实用工具
 * ========================= */
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Net;
using System.Web;

namespace Obsidian.Utils
{
    public class NetUtil
    {
        /// <summary>
        /// IP地址转化为长整形
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <returns>长整形</returns>
        public static int IpToInt(string ip)
        {
            char[] dot = new char[] { '.' };
            string[] ipArr = ip.Split(dot);
            if (ipArr.Length == 3)
                ip = ip + ".0";
            ipArr = ip.Split(dot);

            int ipInt = 0;
            int p1 = int.Parse(ipArr[0]) * 256 * 256 * 256;
            int p2 = int.Parse(ipArr[1]) * 256 * 256;
            int p3 = int.Parse(ipArr[2]) * 256;
            int p4 = int.Parse(ipArr[3]);
            ipInt = p1 + p2 + p3 + p4;
            return ipInt;
        }

        /// <summary>
        /// 整形转化为IP
        /// </summary>
        /// <param name="ipLong">整形</param>
        /// <returns>IP地址</returns>
        public static string IntToIP(int ipInt)
        {
            long seg1 = (ipInt & 0xff000000) >> 24;
            if (seg1 < 0)
                seg1 += 0x100;
            long seg2 = (ipInt & 0x00ff0000) >> 16;
            if (seg2 < 0)
                seg2 += 0x100;
            long seg3 = (ipInt & 0x0000ff00) >> 8;
            if (seg3 < 0)
                seg3 += 0x100;
            long seg4 = (ipInt & 0x000000ff);
            if (seg4 < 0)
                seg4 += 0x100;
            string ip = seg1.ToString() + "." + seg2.ToString() + "." + seg3.ToString() + "." + seg4.ToString();

            return ip;
        }


    }
}
